package com.sino.androiddesign.recyclerviewdemo


import android.content.Context
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import android.util.AttributeSet
import android.view.*
import android.widget.FrameLayout
import android.widget.Scroller
import android.widget.TextView

import com.sino.androiddesign.R
import kotlinx.android.synthetic.main.fragment_skip_remove.*


/**
 * 侧滑删除 或者展示更多
 *
 */
class SkipRemoveFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_skip_remove, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)


        skip_remove_rv.layoutManager = LinearLayoutManager(context)
        skip_remove_rv.adapter = SlidingAdapter(context!!)
        skip_remove_rv.adapter = SlidingAdapter(context!!)


        skip_more_rv.layoutManager = LinearLayoutManager(context)
        var arrayList = ArrayList<String>()
        for (i in 0 until 30) {
            arrayList.add("test $i")
        }
        var deleteAdapter = DeleteAdapter(context!!, arrayList)
        skip_more_rv.adapter = deleteAdapter
        var itemTouchHelper = ItemTouchHelper(DeleteToucherCallBack(deleteAdapter, arrayList))
        itemTouchHelper.attachToRecyclerView(skip_more_rv)
    }

}

class DeleteViewHodler(itemView: View?) : RecyclerView.ViewHolder(itemView) {
    var deleteTv: TextView? = null

    init {
        deleteTv = itemView!!.findViewById(R.id.switch_item_delete_tv)
    }
}

class DeleteAdapter(var context: Context, var datas: ArrayList<String>) : RecyclerView.Adapter<DeleteViewHodler>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DeleteViewHodler {
        var inflate = LayoutInflater.from(context).inflate(R.layout.fragment_switch_item_delete, parent, false)
        return DeleteViewHodler((inflate))
    }

    override fun getItemCount(): Int {
        return datas.size
    }

    override fun onBindViewHolder(holder: DeleteViewHodler, position: Int) {
        holder.deleteTv!!.text = datas[position]
    }
}

class DeleteToucherCallBack(var adapter: DeleteAdapter, var datas: ArrayList<String>) : ItemTouchHelper.Callback() {
    override fun getMovementFlags(recyclerView: RecyclerView?, viewHolder: RecyclerView.ViewHolder?): Int {
        var layoutManager = recyclerView!!.layoutManager
        var mSwip: Int = 0   //滑动

        if (layoutManager is LinearLayoutManager) {
            mSwip = ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
        }
        return makeMovementFlags(0, mSwip)
    }

    override fun onMove(recyclerView: RecyclerView?, viewHolder: RecyclerView.ViewHolder?, target: RecyclerView.ViewHolder?): Boolean {
        return false
    }

    var startX: Int = 0
    var endX: Int = 0
    /**
     * 已经删除过了
     */
    override fun onSwiped(viewHolder: RecyclerView.ViewHolder?, direction: Int) {
        println("110 onSwiped")
        var adapterPosition = viewHolder!!.adapterPosition
        datas.removeAt(adapterPosition)
        adapter.notifyItemRemoved(adapterPosition)

    }

    override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
        super.onSelectedChanged(viewHolder, actionState)
    }

    override fun isItemViewSwipeEnabled(): Boolean {
        return true
    }
}


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
class SlidingAdapter(var context: Context) : RecyclerView.Adapter<SlidingViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SlidingViewHolder {
        return SlidingViewHolder(LayoutInflater.from(context).inflate(R.layout.fragment_skip_item, parent, false))
    }

    override fun getItemCount(): Int {
        return 20
    }

    override fun onBindViewHolder(holder: SlidingViewHolder, position: Int) {

    }
}

class SlidingViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView)

/**
 * 关于对 侧滑的理解:
 * 需要自定义ViewGroup
 *  在android 里面 画布是无限大的 ,view只是基于画布上面就行绘制,而是屏幕只是提供一个可视窗口,类似一个望远镜的功能,
 *  当 子view超出了屏幕的范围我们需要确定它的具体的绘制位置信息也就是它的(left,top,right,bottom)的位置信息
 *  在onFinishInflate()完成绘制的时候就要找出它对应的子视图,onMeasure () 测量的时候 高度为原始的测量高度(measuredHeight)
 *  分别测量子View的原始宽度,并且在Layout()的时候 把超出屏幕的子View 绘制出来sonView.layout(),
 *  注意对滑动事件的处理
 */
class SkipSlidingView : FrameLayout {


    private lateinit var scroller: Scroller

    private lateinit var firstView: TextView
    private lateinit var secondView: TextView

    private var viewHeight: Int = 0
    private var firstWidth: Int = 0
    private var secondWidth: Int = 0


    constructor(mContext: Context) : this(mContext, null)
    constructor(mContext: Context, attributeSet: AttributeSet?) : this(mContext, attributeSet!!, 0)
    constructor(mContext: Context, attributeSet: AttributeSet, defStyle: Int) : super(mContext, attributeSet, defStyle) {

        scroller = Scroller(mContext)
    }

    override fun onFinishInflate() {
        super.onFinishInflate()
        firstView = findViewById(R.id.first_tv)
        secondView = findViewById(R.id.second_tv)
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        viewHeight = measuredHeight
        firstWidth = firstView.measuredWidth
        secondWidth = secondView.measuredWidth

    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
        //需要自己绘制出 secondView 这样才会显示出来
        secondView.layout(firstWidth, 0, firstWidth + secondWidth, viewHeight)
    }

    private var startX: Int = 0
    private var startY: Int = 0
    private var downX: Int = 0
    private var downY: Int = 0

    override fun onTouchEvent(event: MotionEvent?): Boolean {

        when (event!!.action) {
            MotionEvent.ACTION_DOWN -> {
                startX = event.x.toInt()
                startY = event.y.toInt()
                downX = startX
                downY = startY
            }
            MotionEvent.ACTION_MOVE -> {
                var endX = event.x.toInt()
                var endY = event.y.toInt()
                //计算偏移量
                var distanceX = endX - startX
                //scrollx 向左滑动的距离
                var toScrollX = scrollX - distanceX
                if (toScrollX < 0) {
                    toScrollX = 0
                }

                if (toScrollX > secondWidth) {
                    toScrollX = secondWidth
                }
                scrollTo(toScrollX, scrollY)

                startX = event.x.toInt()

                var dx = Math.abs(endX - downX)
                var dy = Math.abs(endY - downY)
                if ((dy < dx) and (dx > 6)) {
                    //当孩子不希望父布局拦截的时候调用
                    parent.requestDisallowInterceptTouchEvent(true)
                }

            }
            MotionEvent.ACTION_UP -> {
                if (scrollX > secondWidth / 2) {
                    openMenu()
                } else {
                    closeMenu()
                }
            }
        }

        return true
    }

    override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
        when (ev!!.action) {
            MotionEvent.ACTION_DOWN -> {  //
                startX = ev.x.toInt()
                startY = ev.y.toInt()
                downX = startX
                downY = startY
            }
            MotionEvent.ACTION_MOVE -> {
                var dx = (ev.x - downX).toInt()
                var dy = (ev.y - downY).toInt()
                if ((dx > dy) and (dx > 6)) {
                    return true
                }
            }
        }
        return super.onInterceptTouchEvent(ev)
    }


    /**
     * 关闭菜单
     *
    public void closeMenu() {
    //0表示menu移动到的目标距离
    int dx = 0 - getScrollX();
    scroller.startScroll(getScrollX(), getScrollY(), dx, getScrollY());
    invalidate();
    if (onStateChangeListener != null) {
    onStateChangeListener.onClose(this);
    }
    }
     */
    private fun closeMenu() {
        var dx = (0 - scrollX).toInt()
        scroller.startScroll(scrollX, scrollY, dx, scrollY)
        invalidate()
    }


    /**
     * /**
     * 打开menu菜单
    */
    public void openMenu() {
    int dx = menuWidth - getScrollX();
    scroller.startScroll(getScrollX(), getScrollY(), dx, getScrollY());
    invalidate();
    if (onStateChangeListener != null) {
    onStateChangeListener.onOpen(this);
    }
    }


     */
    private fun openMenu() {
        var dx = (secondWidth - scrollX).toInt()
        scroller.startScroll(scrollX, scrollY, dx, scrollY)
        invalidate()
    }

    override fun computeScroll() {
        super.computeScroll()
        if (scroller.computeScrollOffset()) {
            scrollTo(scroller.currX, scroller.currY)
            invalidate()
        }
    }


}